<template>
  <re-drawer
    v-model="visible"
    v-bind="$attrs"
    destroy-on-close
    @onConfirm="onSubmit"
    @onClose="onClose"
    @onCancel="onUpdate(false)"
  >
    <div class="p-2x">
      <el-form
        ref="ruleForm"
        :model="state.form"
        :rules="state.rules"
        label-width="100px"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input
            v-model.trim="state.form.name"
            maxlength="50"
            placeholder="请输入字典名称"
            show-word-limit
            class="el-input__limit-fix"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input
            v-model.trim="state.form.code"
            maxlength="50"
            placeholder="请输入字典编码"
            show-word-limit
            class="el-input__limit-fix"
            clearable
          />
        </el-form-item>
        <el-form-item label="字典描述" prop="description">
          <el-input
            v-model="state.form.description"
            type="textarea"
            rows="5"
            maxlength="200"
            show-word-limit
            placeholder="请输入字典描述"
          />
        </el-form-item>
      </el-form>
    </div>
  </re-drawer>
</template>
<script setup lang="ts">
import { reactive, watch, ref, toRaw, type PropType } from 'vue';
import { type FormInstance, ElMessageBox } from 'element-plus';
import type { DictFormFields } from '@/views/system/dict/type';
import ReDrawer from '@/components/ReDrawer';
defineOptions({
  name: 'DrawerUpdate'
});
const $props = defineProps({
  value: {
    type: Object as PropType<DictFormFields>,
    default: () => {},
    required: true
  }
});
const $emits = defineEmits(['confirm', 'update:modelValue']);
const visible = defineModel('modelValue', { default: false });
const state = reactive({
  rules: {
    name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入字典编码', trigger: 'blur' }]
  },
  form: {
    name: '',
    code: '',
    description: ''
  } as DictFormFields
});

const ruleForm = ref<FormInstance | null>(null);

watch(visible, isShow => {
  if (isShow) initData();
});
const initData = () => {
  state.form = { ...$props.value };
};
const onSubmit = () => {
  if (!ruleForm.value) return;
  ruleForm.value.validate(valid => {
    if (!valid) {
      return false;
    }
    $emits('confirm', toRaw(state.form));
    onUpdate(false);
  });
};
const onClose = (done: Function) => {
  ElMessageBox.confirm('确认要取消吗？')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
const onUpdate = value => {
  $emits('update:modelValue', value);
};
</script>
